package scatter.pay.rest.basic;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自定义实现，以支持多个 商户
 * </p>
 *
 * @author yangwei
 * @since 2021-06-27 18:15
 */
public class CustomWxPayServiceImpl  extends WxPayServiceImpl {

	/**
	 * 配置文件
	 */
	private WxPayProperties wxPayProperties;

	public CustomWxPayServiceImpl(WxPayProperties wxPayProperties){

		this.wxPayProperties = wxPayProperties;
	}
	@Override
	public void addConfig(String mchId, WxPayConfig wxPayConfig) {
		super.addConfig(getMchIdByAppCode(mchId), wxPayConfig);
	}

	@Override
	public void removeConfig(String mchId) {
		super.removeConfig(getMchIdByAppCode(mchId));
	}

	@Override
	public void setMultiConfig(Map<String, WxPayConfig> wxPayConfigs) {
		super.setMultiConfig(convertByAppCode(wxPayConfigs));
	}

	@Override
	public void setMultiConfig(Map<String, WxPayConfig> wxPayConfigs, String defaultMchId) {
		super.setMultiConfig(convertByAppCode(wxPayConfigs), getMchIdByAppCode(defaultMchId));
	}

	/**
	 * 转换兼容appCode
	 * @param old
	 * @return
	 */
	private Map<String, WxPayConfig> convertByAppCode(Map<String, WxPayConfig> old){

		Map<String, WxPayConfig> newR = new HashMap<>(old.size());
		for (String k : old.keySet()) {
			newR.put(getMchIdByAppCode(k),old.get(k));
		}
		return newR;
	}
	@Override
	public boolean switchover(String mchId) {
		return super.switchover(getMchIdByAppCode(mchId));
	}

	@Override
	public WxPayService switchoverTo(String mchId) {
		return super.switchoverTo(getMchIdByAppCode(mchId));
	}


	/**
	 * 根据appCode查找配置的mchId,如果没有找到，返回appCode
	 * @param appCode
	 * @return 返回appCode如果没有找到，否则返回mchId
	 */
	private String getMchIdByAppCode(String appCode){

		if (wxPayProperties.getConfigs() != null) {
			return wxPayProperties.getConfigs().stream()
					.filter(item -> StringUtils.equals(appCode, item.getAppCode()) || StringUtils.equals(appCode, item.getAppId()))
					.map(WxPayProperties.WxPayConfig::getMchId)
					.findFirst().orElse(appCode);
		}

		return appCode;
	}
}
